package com.codeplay.service.impl;

import com.codeplay.entity.Content;
import com.codeplay.repository.ContentRepository;
import com.codeplay.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ContentServiceImpl implements ContentService {

    private final ContentRepository contentRepository;

    @Autowired
    public ContentServiceImpl(ContentRepository contentRepository) {
        this.contentRepository = contentRepository;
    }

    @Override
    public Content createContent(Content content) {
        return contentRepository.save(content);
    }

    @Override
    public Content getContentById(Long id) {
        return contentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Content not found"));
    }

    @Override
    public List<Content> getContentsByChapterId(Long chapterId) {
        return contentRepository.findByChapterIdOrderByOrderIndexAsc(chapterId);
    }

    @Override
    public Content updateContent(Content content) {
        Content existingContent = getContentById(content.getId());
        existingContent.setTitle(content.getTitle());
        existingContent.setContentType(content.getContentType());
        existingContent.setContent(content.getContent());
        existingContent.setOrderIndex(content.getOrderIndex());
        return contentRepository.save(existingContent);
    }

    @Override
    public void deleteContent(Long id) {
        contentRepository.deleteById(id);
    }

    @Override
    public Content getNextContent(Long chapterId, Integer currentOrderIndex) {
        return contentRepository.findByChapterIdAndOrderIndex(chapterId, currentOrderIndex + 1);
    }

    @Override
    public Content getPreviousContent(Long chapterId, Integer currentOrderIndex) {
        return contentRepository.findByChapterIdAndOrderIndex(chapterId, currentOrderIndex - 1);
    }
} 